<template>
  <lb-layout
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
    :paddBottom="5"
  >
    <!-- <lb-layout> -->
    <el-row :gutter="20" class="flex-row">
      <el-tree
        :data="dingDeptList"
        :props="defaultProps"
        @node-click="handleNodeClick"
        class="bg left"
      ></el-tree>
      <div class="bg right">
        <el-row>
          <el-col :span="24">
            <aps-form
              :config="apsForm.formConfig"
              :model="apsForm.formData"
              :formRef="apsForm.formRef"
              :labelWidth="apsForm.labelWidth"
              ref="form"
            ></aps-form>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" class="table-box1">
            <lb-table
              :column="tableData.column"
              :data="tableData.data"
              background
              height="730"
              pagination
              layout="total, sizes, prev, pager, next, jumper"
              :page-sizes="[20, 40, 60, 80]"
              :pager-count="5"
              :current-page.sync="currentPage"
              :page-size="pageSize"
              @size-change="handleSizeChange"
              @p-current-change="handleCurrentChange"
              :total="total"
            >
            </lb-table>
          </el-col>
        </el-row>
      </div>
    </el-row>
    <!-- </lb-layout> -->
    <component
      :is="modelName"
      :modelWay="flag"
      :statusFlag="statusFlag"
      :id="id"
      :employeeCode="employeeCode"
      :accountId="accountId"
      :visible.sync="show"
      @close="close"
    ></component>
  </lb-layout>
</template>

<script>
import zTree from "@/components/zTree";
import auth from "@/plugins/auth";
import operate from "@/views/configuration/basicdata/binding/components/operate.vue";
import {
  getDepttree,
  list,
  syncDing,
  putUnbundle,
} from "@/api/basicdata/binding.js";
// import { deepClone } from "@/utils/index";
export default {
  components: {
    zTree,
    operate,
  },
  dicts: ["energy_type", "zzd_status"],
  data() {
    return {
      // 弹窗
      modelName: "",
      id: null,
      show: false,
      flag: "",
      statusFlag: "",
      employeeCode: null,
      accountId: null,
      // 树
      dingDeptList: [],
      choseCode: null,
      defaultProps: {
        children: "children",
        label: "name",
      },
      apsForm: {
        formRef: "form",
        labelWidth: "120px",
        formData: {},
        formConfig: {
          formAttr: {
            inline: true,
            size: "small",
          },
          properties: {
            //这里是渲染查询表单的表头和类型的数据
            name: {
              typeName: "el-input",
              clearable: true,
              placeholder: "请输入用户名称",
            },
            status: {
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.zzd_status.some((item) => {
                  arr.push(item);
                });
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().status;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择员工状态",
                        value: valNum,
                        clearable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("status", value);
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
          },
          formSoltButton: [
            {
              label: "搜索",
              type: "primary",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-search",
              click: this.handlerSearchDetail,
            },
            {
              label: "重置",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-refresh-left",
              click: this.handleReset,
            },
            {
              label: "同步",
              type: "warning",
              plain: true,
              typeName: "el-button",
              size: "small",
              icon: "el-icon-refresh",
              display: true,
              click: this.handleSync,
            },
          ],
        },
      },
      tableData: {
        column: [
          {
            prop: "index",
            label: "编号",
            showOverflowTooltip: true,
          },
          {
            prop: "name",
            label: "姓名",
            showOverflowTooltip: true,
          },
          {
            prop: "job",
            label: "职务",
            showOverflowTooltip: true,
          },
          // {
          //   prop: "msg",
          //   label: "上级能耗终端",
          //   showOverflowTooltip: true,
          // },
          {
            prop: "dept",
            label: "部门",
          },
          {
            prop: "account",
            label: "账号",
            width: 150,
          },
          {
            prop: "status",
            label: "能耗平台状态",
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.zzd_status}
                    value={scope.row.status}
                  />
                </div>
              );
            },
            // render: (h, params) => {
            //   let testType =
            //     params.row.status == null ? "" : params.row.status.toString();
            //   let typeArr = this.dict.type.zzd_status;
            //   let typeName = "";
            //   typeArr.forEach((element) => {
            //     if (element.value == testType) {
            //       typeName = element.label;
            //     }
            //   });
            //   return h("div", {}, typeName);
            // },
          },
          {
            label: "操作",
            width: "180",
            fixed: "right",
            render: (h, scope) => {
              let that = this;
              let a, b, c;
              let inline = {
                float: "left",
              };
              if (scope.row.status == 0 || scope.row.status == 2) {
                a = (
                  <el-button
                    v-hasPermi={["system:dingTalk:edit"]}
                    type="text"
                    size="small"
                    icon="el-icon-lock"
                    onClick={() => {
                      that.openDiago("operate", scope.row, "binding");
                    }}
                  >
                    绑定
                  </el-button>
                );
              } else {
                a = <div style="display:none"></div>;
              }
              if (scope.row.status == 1) {
                b = (
                  <el-button
                    v-hasPermi={["system:dingTalk:edit"]}
                    type="text"
                    size="small"
                    icon="el-icon-unlock"
                    onClick={() => {
                      that.handleUnbundle(scope.row);
                    }}
                    class="text-danger"
                  >
                    解绑
                  </el-button>
                );
                c = (
                  <el-button
                    v-hasPermi={["system:user:edit"]}
                    type="text"
                    size="small"
                    icon="el-icon-edit"
                    onClick={() => {
                      that.openDiago("operate", scope.row, "edit");
                    }}
                  >
                    修改
                  </el-button>
                );
              } else {
                b = <div style="display:none"></div>;
                c = <div style="display:none"></div>;
              }
              return (
                <div style={inline}>
                  {a}
                  {b}
                  {c}
                </div>
              );
            },
          },
        ],
        data: [],
      },
      currentPage: 1,
      pageSize: 20,
      total: 0,
    };
  },
  created() {},
  mounted() {
    this.judgePermi();
    this.requestDepttree();
    this.initData();
  },
  methods: {
    judgePermi() {
      if (auth.hasPermi("system:dingTalk:synchronised")) {
        this.apsForm.formConfig.formSoltButton[2].display = false;
      }
    },
    // todo 获取部门树
    requestDepttree() {
      getDepttree()
        .then((res) => {
          // console.log(res);
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let brr = res?.data ?? [];
          this.dingDeptList = brr;
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!20080");
        });
    },
    // 节点单击事件
    handleNodeClick(data) {
      // console.log(data);
      this.choseCode = data.code;
      setTimeout(() => {
        this.handlerSearchDetail();
      }, 200);
    },
    async initData(data) {
      let that = this;
      let query = {
        organizationCode: this.choseCode,
        ...data,
      };
      query.pageSize = this.pageSize;
      query.pageNum = this.currentPage;
      that.$store.commit("app/updateApiCount", "add");
      await list(query)
        .then((res) => {
          // console.log(res);
          that.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            that.$message.warning(res.msg);
            return false;
          }
          that.resDeal(res?.rows ?? []);
          that.total = res?.total ?? 0;
        })
        .catch((err) => {
          that.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!20081");
        });
    },
    // 列表响应处理
    resDeal(arr) {
      let brr = [];
      arr.map((item, index) => {
        let obj = {
          index: index,
          employeeCode: item?.employeeCode ?? "",
          name: item?.name ?? "",
          job: item?.govEmpPosJob ?? "",
          dept: item?.deptName ?? "默认单位",
          account: item?.sysAccountName ?? "",
          accountId: item?.accountId ?? null,
          status: item?.status ?? null,
          id: item?.sysUserId ?? null,
        };
        brr.push(obj);
      });
      this.tableData.data = brr;
    },
    handlerSearchDetail(val) {
      const data = {
        ...this.$refs?.form?.getFieldsValue(),
      };
      this.initData(data);
      // 筛选数据
      // this.tableData.data = this.handleScreen(data, this.alltableData);
    },
    // 筛选数据
    // handleScreen(form, list) {
    //   let arr = list;
    //   Object.keys(form).forEach((e) => {
    //     if (form[e] == undefined || form[e] == "") return arr;
    //     arr = arr.filter((p) => p[e].indexOf(form[e]) > -1); //匹配成功返回
    //   });
    //   // console.log(arr, "筛选结果");
    //   return arr;
    // },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.handlerSearchDetail();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handlerSearchDetail();
    },
    //重置
    handleReset() {
      // this.dingDeptList = [];
      // this.$refs.tree.$refs.tree.setCurrentKey(null);
      this.$refs?.form?.resetFields();
      this.handlerSearchDetail();
    },
    // 同步
    handleSync() {
      syncDing()
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$modal.msgSuccess("同步成功");
          this.handlerSearchDetail();
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!20089");
        });
    },
    // 解绑
    handleUnbundle(row) {
      this.$confirm("确认解绑该用户?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.getUnbundlerequest(row.employeeCode);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    // todo 解绑请求
    getUnbundlerequest(code) {
      putUnbundle(code)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$modal.msgSuccess("解绑成功");
          this.handlerSearchDetail();
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!20084");
        });
    },
    // 弹出层开
    openDiago(name, row, flag) {
      console.log(row, "row");
      if (flag == "edit") {
        this.id = row?.id ?? null;
        setTimeout(() => {
          this.show = true;
        }, 100);
      } else if (flag == "binding") {
        if (row.status == 2) {
          this.id = row?.id ?? null;
          setTimeout(() => {
            this.show = true;
          }, 100);
        } else {
          this.id = null;
          setTimeout(() => {
            this.show = true;
          }, 100);
        }
      }
      this.employeeCode = row?.employeeCode ?? "";
      this.accountId = row?.accountId ?? null;
      if (typeof this.accountId == "number") {
        this.accountId = this.accountId.toString();
      }
      this.modelName = name;
      this.statusFlag = row?.status ?? null;
      this.flag = flag;
    },
    // 弹出层关
    close(status) {
      this.show = false;
      if (status) {
        this.handlerSearchDetail();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/styles/mixin.scss";
.bg {
  background-color: #ffffff !important;
}
::v-deep .flex-row {
  display: flex;
  min-height: 88vh;
  .left {
    width: 300px;
    margin-right: 20px;
    .el-tree {
      @include scrollBar2;
    }
  }
  .right {
    flex: 1;
    width: 100%;
    overflow: hidden;
  }
}
.table-box {
  max-height: 400px;
  overflow-y: scroll;
  @include scrollBar2;
}
</style>
